package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.alibaba.sdk.android.media.upload.UploadListener;
import com.alibaba.sdk.android.media.upload.UploadTask;
import com.alibaba.sdk.android.media.utils.FailReason;
import com.arlen.photo.photopickup.presenter.HeadPresenter;
import com.arlen.photo.photopickup.util.FileSizeUtil;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.data.AdvertListData;
import com.wbao.dianniu.listener.IAdvertAddListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.manager.AdvertAddManager;
import com.wbao.dianniu.update.ExchangeHisHelper;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PermissionUtils;
import com.wbao.dianniu.utils.PictureDownloadUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 发布广告
 * <p>
 * Created by yejianjun on 2018/5/28.
 */

public class SendAdActivity extends BaseActivity implements IAdvertAddListener {

    private final int IMAGE_OPEN = 1; // 打开图片标记
    private Button rightBtn;
    private ImageButton addImageBtn;
    private Dialog pDialog;
    private EditText et_content;
    private EditText et_addUrl;
    private boolean isChosePic = false;
    private AdvertAddManager manager;
    private String advertImage;
    private AdvertListData data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_send_ad);
        initView();
        initData();
        pullData();
    }

    private void initView() {
        setTitleName("发广告");
        rightBtn = getRightTextButton();
        rightBtn.setText("提交");
        rightBtn.setOnClickListener(this);
        addImageBtn = (ImageButton) findViewById(R.id.send_ad_imageBtn);
        addImageBtn.setOnClickListener(this);
        et_content = (EditText) findViewById(R.id.send_ad_content);
        et_addUrl = (EditText) findViewById(R.id.send_ad_url);
    }

    private void initData() {
        isChosePic = false;
        manager = new AdvertAddManager(this);
        manager.addAdvertAddListener(this);
    }

    // 如果是修改广告 加载数据到对应内容里面
    private void pullData() {
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            data = new AdvertListData();
            data.setId(bundle.getInt(Const.BUNDLE_ID));
            data.setContent(bundle.getString(Const.BUNDLE_CONTENT, ""));
            data.setToPageUrl(bundle.getString(Const.BUNDLE_ADVERTTOPAGEURL, ""));
            data.setAdvertImage(bundle.getString(Const.BUNDLE_HEADPIC, ""));
            loadingData(data);
        }
    }

    private void loadingData(AdvertListData listData) {
        if (null == listData) {
            return;
        }
        et_content.setText(listData.getContent() == null ? "" : listData.getContent());
        PictureDownloadUtils.loadingAdImage(this, addImageBtn, listData.getAdvertImage());
        et_addUrl.setText(listData.getToPageUrl() == null ? "" : listData.getToPageUrl());
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.right_button:
                String content = et_content.getText().toString().trim();
                String url = et_addUrl.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    Notification.toast(this, "内容不能为空");
                    et_content.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(url)) {
                    Notification.toast(this, "链接不能为空");
                    et_addUrl.requestFocus();
                    return;
                }
                String urlmat = "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?";
                Pattern pattern = Pattern.compile(urlmat);
                Matcher matcher = pattern.matcher(url);
                if (!matcher.find()) {
                    Notification.toast(this, "广告链接不是合法的网址");
                    et_addUrl.requestFocus();
                    return;
                }
                if (!isChosePic) {
                    Notification.toast(this, "请选择广告图片");
                    return;
                }
                pDialog = LoadingWaitDialog.createLoadingDialog(this, "");
                pDialog.show();
                Integer id = null;
                if (null != data) {
                    id = data.getId();
                }
                manager.advertAdd(id, content, advertImage, url);
                break;
            case R.id.send_ad_imageBtn:
                //选择图片
                PermissionUtils.getInstance().intentToPhoto(SendAdActivity.this, IMAGE_OPEN, 1, null);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == IMAGE_OPEN) {
            Uri uri = data.getData();
            if (!TextUtils.isEmpty(uri.getAuthority())) {
                //查询选择图片
                Cursor cursor = getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA},
                        null, null, null);
                //返回 没找到选择图片
                if (null == cursor) {
                    return;
                }
                //光标移动至开头 获取图片路径
                cursor.moveToFirst();
                String pathImage = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                cursor.close();

                Intent pIntent = new Intent();
                pIntent.setClass(this, AdImageCutActivity.class);
                pIntent.putExtra(Const.BUNDLE_DATA, pathImage);
                startActivityForResult(pIntent, 110);
            }
        } else if (requestCode == 110 && resultCode == RESULT_OK) {
            String cachePath = data.getStringExtra("cachePath");
            String uploadName = data.getStringExtra("headPic");
            if (null != cachePath && null != uploadName) {
                pDialog = LoadingWaitDialog.createLoadingDialog(this, "");
                pDialog.setCancelable(false);
                pDialog.show();
                advertImage = uploadName;
                //图片选择成功，上传图片到cdn，得到cdn的路径
                HeadPresenter presenter = new HeadPresenter(SendAdActivity.this);
                presenter.addUploadListener(new MyUploadLister(uploadName, cachePath));
                presenter.uploadImageNotCompress(cachePath, uploadName);
            }

        }

    }

    private boolean processImage(String path) {
        // 按比例裁剪
        boolean ret = false;
        double size = FileSizeUtil.getFileOrFilesSize(path, 2);
        if (size > 1024) {
            Notification.toast(this, "图片尺寸过大，请重新选择图片");
            return ret;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//这个参数设置为true才有效，
        Bitmap bmp = BitmapFactory.decodeFile(path, options);//这里的bitmap是个空
        int outHeight = options.outHeight;
        int outWidth = options.outWidth;
        if (outWidth < outHeight) {
            Notification.toast(this, "尺寸不合格，请重新上传");
            return ret;
        }

        return true;
    }

    @Override
    public void onAdvertAddFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        Notification.toast(this, errorMsg == null ? "" : errorMsg);
    }

    @Override
    public void onAdvertAddSuccess() {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        AdvertListData data = new AdvertListData();
        data.setContent(et_content.getText().toString());
        data.setStatus(1);
        data.setToPageUrl(et_addUrl.getText().toString());
        ExchangeHisHelper.getInstance().addOneExchange(data);
        finish();
    }


    /**
     * 上传图片事件监听
     */
    class MyUploadLister implements UploadListener {
        ;
        private String fileName;
        private String pathImage;

        public MyUploadLister(String fileName, String pathImage) {
            this.fileName = fileName;
            this.pathImage = pathImage;
        }

        @Override
        public void onUploading(UploadTask uploadTask) {
        }

        @Override
        public void onUploadFailed(UploadTask uploadTask, FailReason arg1) {
            // TODO Auto-generated method stub
            if (null != pDialog && pDialog.isShowing()) {
                pDialog.dismiss();
            }
            Notification.toast(SendAdActivity.this, "上传失败");
//            UploadTask.Result result = uploadTask.getResult();
//            String requestId = (null == result ? "null" : result.requestId);

        }

        @Override
        public void onUploadComplete(UploadTask arg0) {
            if (null != pDialog && pDialog.isShowing()) {
                pDialog.dismiss();
            }
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(pathImage, options);
            Bitmap bmp = FileSizeUtil.compressBitmap(pathImage, addImageBtn.getWidth(), addImageBtn.getWidth() * options.outHeight / options.outWidth);
            addImageBtn.setImageBitmap(bmp);
            isChosePic = true;
        }

        @Override
        public void onUploadCancelled(UploadTask arg0) {
            if (null != pDialog && pDialog.isShowing()) {
                pDialog.dismiss();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager)
            manager.removeAdvertAddListener(this);
    }
}
